package com.itheima.leetcode;

/**
 * <h1>买卖股票的最佳时机</h1>
 * <h2>某一天买入股票，未来任意一天卖出，只卖一次，求最大利润</h2>
 * i尝试买入，j尝试卖出<br>
 * <li>遇到涨i不变，i++</li>
 * <li>遇到跌i变j，j++</li>
 */
public class SharesILeetcode121 {

    static int maxProfit(int[] prices) {
        int i = 0;
        int j = 1;
        int max = 0;
        while (prices.length > j) {
            if (0 < prices[j] - prices[i]) { // 涨
                max = Math.max(max, prices[j] - prices[i]);
                j++;
            } else { // 跌
                i = j;
                j++;
            }
        }
        return max;
    }

    public static void main(String[] args) {
        System.out.println(maxProfit(new int[]{7, 1, 5, 3, 6, 4})); // 5
        System.out.println(maxProfit(new int[]{9, 3, 12, 1, 2, 3})); // 9
    }
}
